package com.burgeon.backend.service.Impl;


import com.burgeon.backend.Rest.Tags.*;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.VipAttrib;
import com.burgeon.backend.entity.VipTags;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.CodeService;
import com.burgeon.backend.service.VipTageService;
import com.burgeon.backend.service.WechatService;
import com.burgeon.backend.service.ex.ErrorDataException;
import com.burgeon.backend.verification.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;

@Service
public class VipTagsServiceImpl implements VipTageService {
    private final static Log logger = LogFactory.getLog(VipTageService.class);

    @Autowired
    private WechatService wechatService;
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public HashMap GetVipTagsWX(String account) throws ErrorDataException {
        String accessToken = wechatService.GetAccesTokenByAccount(account);
        String url = "https://api.weixin.qq.com/cgi-bin/tags/get?" +
                "access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.getForObject(url, String.class);
        ArrayList syn = new ArrayList();
        HashMap value = new HashMap();
        ArrayList<VipTags> data = new ArrayList<VipTags>();
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONArray jsonArray = jsonObject.getJSONArray("tags");

            ArrayList<String> typelist = new ArrayList<String>();
            ArrayList<String> typeid = new ArrayList<String>();
            int t = 0;
            HashMap hashMap = new HashMap();
            for (int i = 0; i < jsonArray.length(); i++) {
                VipTags vipTags = new VipTags();

                String id = jsonArray.getJSONObject(i).getString("id");
                vipTags.setId(id);
                String name[];
                try {
                    HashMap map = new HashMap();
                    map.put("name", jsonArray.getJSONObject(i).getString("name"));
                    map.put("id", id);
                    syn.add(map);
                    name = jsonArray.getJSONObject(i).getString("name").split(":");
                    if (name.length != 2) {
                        throw new Exception();
                    }
                    vipTags.setType(name[0]);
                    vipTags.setName(name[1].replace(":", ""));
                } catch (Exception e) {
                    name = new String[]{"未分组", jsonArray.getJSONObject(i).getString("name")};
                    vipTags.setType(name[0]);
                    vipTags.setName(name[1]);
                }

                vipTags.setCount(jsonArray.getJSONObject(i).getString("count"));

                boolean bol = false;
                for (String o : typelist) {
                    if (name[0].equals(o)) {
                        bol = true;
                    }
                }
                vipTags.setTypeid(String.valueOf(t));
                if (!bol) {
                    t++;
                    typelist.add(name[0]);
                    hashMap.put(name[0],String.valueOf(t));

                    typeid.add(String.valueOf(t));
                }
                vipTags.setTypeid(hashMap.get(name[0]).toString());
                data.add(vipTags);
            }
            value.put("syn", syn);
            value.put("type", typelist);
            value.put("typeid", typeid);
            value.put("data", data);
        } catch (JSONException e) {
            logger.error(e.getMessage()+"未获取微信接口tags数据");

            throw new ErrorDataException("未获取微信接口tags数据");
        }

        return value;
    }

    @Override
    public HashMap GetVipTagsBos(String account) throws ErrorDataException {
        Info info = GetInfo(account);
        GetTagsALL getTagsALL = new GetTagsALL(info.getUrl(), info.getAccount(), info.getPassword());
        HashMap data = new HashMap();
        try {
            data = getTagsALL.getData();
        } catch (Exception e) {
            logger.error(e.getMessage()+"获取viptagsbos错误");

            throw new ErrorDataException("未获取Bos接口tags数据");
        }
        return data;
    }

    @Override
    public void DelVipTagsWX(String id, String account) throws ErrorDataException {

        try {
            String accessToken = wechatService.GetAccesTokenByAccount(account);
            String url = "https://api.weixin.qq.com/cgi-bin/tags/delete?" +
                    "access_token=" + accessToken;
            RestTemplate restTemplate = new RestTemplate();
            String data = "{   \"tag\":{        \"id\" : " + id + "   } } ";
            String str = restTemplate.postForObject(url, data, String.class);
        }catch (Exception e){
            logger.error(e.getMessage()+"微信删除Tags接口错误");
            throw new ErrorDataException("微信删除Tags接口错误");
        }
    }

    @Override
    public void AddVipTagsWx(String name, String account) throws ErrorDataException {
        String accessToken = wechatService.GetAccesTokenByAccount(account);
        String URL = "https://api.weixin.qq.com/cgi-bin/tags/create?" +
                "access_token=" + accessToken;

        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);// 设置是否允许数据写入
            connection.setDoOutput(true);// 设置是否允许参数数据输出
            connection.setConnectTimeout(5000);// 设置链接响应时间
            connection.setReadTimeout(10000);// 设置参数读取时间
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            // 提交请求
            out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            Query query = new Query();

            String data = "{   \"tag\" : {     \"name\" : \"" + name + "\"  } } ";
            out.write(data);
            out.flush();
            // 读取返回参数
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                result.append(temp);
            }
        } catch (Exception e) {
            logger.error(e.getMessage()+"微信添加Tags接口错误");

            throw new ErrorDataException("微信添加Tags接口错误");
        }
    }

    @Override
    public void MakeVipTag(String[] phones,VipAttrib vipAttrib,String account) throws ErrorDataException {
        Info info = GetInfo(account);
        FindTagsIdByVip findTagsIdByVip = new FindTagsIdByVip(info.getUrl(), info.getAccount(), info.getPassword());
        ModVipTagsBos modVipTagsBos = new ModVipTagsBos(info.getUrl(), info.getAccount(), info.getPassword());
        InsertVipTagsBos insertVipTagsBos = new InsertVipTagsBos(info.getUrl(), info.getAccount(), info.getPassword());

        for (String phone : phones) {
            try {
                modVipTagsBos.getData(findTagsIdByVip.getData(phone), vipAttrib);
            } catch (Exception e) {
                try {
                    insertVipTagsBos.getData(phone, vipAttrib);
                } catch (Exception ex) {
                    logger.error(e.getMessage()+"添加vip标签错误");

                    throw new ErrorDataException("添加vip标签错误");
                }
            }
        }
    }

    @Override
    public void DelVipTagsBos(String id, String account) throws ErrorDataException {
        Info info = GetInfo(account);
        DeleteTagsBos deleteTagsBos = new DeleteTagsBos(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            deleteTagsBos.getData(id);
        } catch (Exception e) {
            logger.error(e.getMessage()+"Bos删除vip标签错误");

            throw new ErrorDataException("Bos删除vip标签错误");
        }
    }

    @Override
    public void AddVipTagsBos(String tid, String name, String account)  throws ErrorDataException{
        Info info = GetInfo(account);
        AddTagsBos addTagsBos = new AddTagsBos(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            addTagsBos.getData(tid,name);
        } catch (Exception e) {
            logger.error(e.getMessage()+"Bos添加vip标签接口错误");

            throw new ErrorDataException("微信添加Tags接口错误");
        }

    }

    @Override
    public void ModTagsTypeName(String id, String name, String account)  throws ErrorDataException {
        Info info = GetInfo(account);
        ModTagsTypeNameBos modTagsTypeNameBos = new ModTagsTypeNameBos(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            modTagsTypeNameBos.getData(id,name);
        } catch (Exception e) {
            logger.error(e.getMessage()+"Bos修改标签类名错误");

            throw new ErrorDataException("Bos修改标签类名错误");
        }
    }


    private Info GetInfo(String account) {
        return accountMapper.GetAccData(account);
    }


}
